import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/authentication.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/common/LoginDto.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/pages/login/LoginCard.dart';
import 'package:ichinesereader/pages/common/forgetpassword.dart';
import 'package:ichinesereader/pages/individual/renewsubscription.dart';
import 'package:ichinesereader/pages/login/strongPassword.dart';
import 'package:ichinesereader/themes/buttonStyles.dart';
import 'package:ichinesereader/utils/encrypt.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/widgets/dialogs/roleChoose.dart';
import 'package:reactive_forms/reactive_forms.dart';

class LoginReactive extends StatefulWidget {
  static const String routeName = '/login';

  @override
  _LoginReactiveState createState() => _LoginReactiveState();
}

class _LoginReactiveState extends State<LoginReactive> {
  LoginDto logindto = new LoginDto();

  //AuthMessage _authMessage = new AuthMessage();
  final LoginController _loginManager = Get.find();
  final LoginFormModel formModel = LoginFormModel();
  late FormGroup form;

  AppButtonStyles _appButtonStyles = new AppButtonStyles();
  String message = '';
  bool value = false;
  bool _rememberme = false;
  String _userName = '';
  String _passWord = '';

  void _login(String username, String password, bool remember) async {
    logindto.userName = username.trim();
    logindto.password = password.trim();
    logindto.sessionType = 'WEB';

    try {
      await _loginManager.login(logindto, remember).then((_authMessage) {
        Log.debug('message after login submit');
        if (_authMessage.status == LoginStatusKey.logged_in) {
          switch (_loginManager.userRole.value) {
            case Constants.NanhaiRole_Student:
              {
                Get.offAllNamed('/student/home');
                break;
              }
            case Constants.NanhaiRole_Teacher:
              {
                Get.offAllNamed('/teacher/home');
                break;
              }
            case Constants.NanhaiRole_SchoolAdmin:
              {
                Get.offAllNamed('/schooladmin/home');
                break;
              }
            case Constants.NanhaiRole_Individual:
              {
                Get.offAllNamed('/individual/home');
                break;
              }
            case Constants.NanhaiRole_Parent:
              {
                Get.offAllNamed('/parent/home');
                break;
              }
            default:
              Get.offAllNamed('/error');
              break;
          }
        } else if (_authMessage.status == LoginStatusKey.has_placement) {
          Log.debug('login and redirect to placement pagee');
          Get.offAllNamed('/placement', arguments: false);
        } else if (_authMessage.status == LoginStatusKey.need_strong_password) {
          Log.debug('login and redirect to strong password pagee');

          Get.to(() => ResetStrongUserPasswordPage(
              isTeacherOrSchooladmin: true,
              currentPassword: _passWord,
              remember: _rememberme));
        } else {
          Log.debug('login failure from login page');

          message = _authMessage.message.toString();
          showSnackMsg(message);
          // Get.snackbar('Message'.tr, message.tr,
          //     backgroundColor: Get.theme.primaryColorDark,
          //     colorText: Get.theme.primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
          if (message == 'Account Expired/Subscription Cancelled') {
            if (GetPlatform.isAndroid || GetPlatform.isIOS) {
              Get.to(() => InAppWebViewIndividualRenewSubscriptionScreen());
            } else {
              launchInWebViewWithJavaScript(
                  '${Constants.BaseURL}icr/student/individualPay?webview=true');
            }
          } else {
            //_loginManager.removeToken();
          }
        }
      });
    } catch (error) {
      showSnackMsg(error.toString());
      // Get.snackbar('Message'.tr, error.toString(),
      //     backgroundColor: Get.theme.primaryColorDark,
      //     colorText: Get.theme.primaryColorLight,
      //     snackPosition: SnackPosition.BOTTOM);
    }
  }

  @override
  void initState() {
    super.initState();
    form = formModel.form;
    try {
      var box = Hive.box('appconfig');
      if (box.get(CacheManagerKey['password'].toString()) != null &&
          box.get(CacheManagerKey['password'].toString()) != '') {
        _userName = box.get(CacheManagerKey['username'].toString());
        EncryptData.decryptAES(box.get(CacheManagerKey['password'].toString()));
        _passWord = EncryptData.decrypted;
        _rememberme = true;
        if (_userName != '') form.control('username').value = _userName;
        if (_passWord != '') form.control('password').value = _passWord;
        form.control('remember').value = _rememberme;
      }
    } catch (error) {
      Log.debug(error);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // final isSmallScreen =
    //     MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;

    return Scaffold(
      resizeToAvoidBottomInset: true,
      floatingActionButton: GetPlatform.isWeb
          ? FloatingActionButton(
              tooltip: 'Go to OLD version'.tr,
              onPressed: () {
                launchInWebViewWithJavaScript(
                    'https://ichinesereader.com/icr/login');
              },
              backgroundColor: Colors.green,
              child: const Icon(Icons.navigation),
            )
          : null,
      body: Container(
        height: MediaQuery.of(context).size.height,
        decoration: Get.isDarkMode
            ? BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color(0xff111111),
                    Color(0xff222222),
                    Color(0xff222222),
                    Color(0xff333333),
                    Color(0xff444444),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment(2.0, 1.0),
                ),
              )
            : BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Get.theme.primaryColorDark,
                    AppTheme.colors.primary,
                    AppTheme.colors.primary,
                    AppTheme.colors.babyBlue,
                    Get.theme.primaryColorLight,
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment(2.0, 1.0),
                ),
              ),
        child: Center(
          child: Container(
            height: 530,
            width: 530,
            child: ReactiveForm(
              formGroup: form,
              child: Container(
                decoration: BoxDecoration(
                  color: Get.isDarkMode
                      ? Colors.blueGrey.withOpacity(0.1)
                      : Colors.white.withOpacity(0.2),
                  boxShadow: [
                    BoxShadow(
                      blurRadius: 2,
                      spreadRadius: 1,
                      color: Get.isDarkMode
                          ? Colors.blueGrey.withOpacity(0.1)
                          : Colors.white.withOpacity(0.1),
                      offset: Offset(-27, -27),
                    ),
                    BoxShadow(
                      blurRadius: 2,
                      spreadRadius: 1,
                      color: Get.isDarkMode
                          ? Colors.blueGrey.withOpacity(0.1)
                          : Colors.white.withOpacity(0.1),
                      offset: Offset(27, 27),
                    ),
                  ],
                ),
                padding: EdgeInsets.symmetric(
                  vertical: 70,
                ),
                child: Center(
                  child: Stack(
                    children: [
                      Container(
                        width: 350,
                        height: 50,
                        decoration: BoxDecoration(
                          color: Get.isDarkMode
                              ? Colors.black.withOpacity(0.2)
                              : Colors.white.withOpacity(0.7),
                        ),
                        child: ReactiveTextField(
                          formControlName: 'username',
                          maxLines: 1,
                          autocorrect: false,
                          decoration: InputDecoration(
                            prefixIcon: Icon(
                              Icons.perm_identity_rounded,
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark.withOpacity(0.8)
                                  : Get.theme.primaryColorDark,
                            ),
                            hintText: 'Username'.tr,
                            hintStyle: TextStyle(
                              fontFamily: 'Montserrat',
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark.withOpacity(0.8)
                                  : Get.theme.primaryColorDark,
                            ),
                          ),
                          validationMessages: {
                            ValidationMessage.required: (_) =>
                                'Username must not be empty!'.tr,
                          },
                        ),
                      ),
                      Container(
                        width: 350,
                        height: 50,
                        margin: EdgeInsets.symmetric(
                          vertical: 64,
                        ),
                        decoration: BoxDecoration(
                          color: Get.isDarkMode
                              ? Colors.black.withOpacity(0.2)
                              : Colors.white.withOpacity(0.7),
                        ),
                        child: ReactiveTextField(
                          formControlName: 'password',
                          maxLines: 1,
                          autocorrect: false,
                          obscureText: true,
                          style: TextStyle(
                            fontFamily: 'Montserrat',
                          ),
                          decoration: InputDecoration(
                            prefixIcon: Icon(
                              Icons.password_rounded,
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark.withOpacity(0.8)
                                  : Get.theme.primaryColorDark,
                            ),
                            hintText: 'Password'.tr,
                            hintStyle: TextStyle(
                              fontFamily: 'Montserrat',
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark.withOpacity(0.8)
                                  : Get.theme.primaryColorDark,
                            ),
                          ),
                          validationMessages: {
                            ValidationMessage.minLength: (_) =>
                                'Password min length 6 characters'.tr,
                          },
                        ),
                      ),
                      Container(
                        width: 350,
                        margin: EdgeInsets.symmetric(
                          vertical: 120,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              child: Align(
                                alignment: Alignment.topLeft,
                                child: Row(
                                  children: [
                                    ReactiveCheckbox(
                                      checkColor: Colors.white,
                                      formControlName: 'remember',
                                    ),
                                    Text(
                                      'Remember Me'.tr,
                                      overflow: TextOverflow.ellipsis,
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontFamily: 'Montserrat',
                                        color: AppTheme.colors.textCyanLight,
                                        fontSize: 14.0,
                                        letterSpacing: 1.0,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Container(
                                child: Align(
                              alignment: Alignment.topRight,
                              child: TextButton(
                                onPressed: () {
                                  Get.to(() => ResetPasswordTabsPage());
                                },
                                child: Text(
                                  'Forgot Password'.tr,
                                  style: TextStyle(
                                      fontFamily: 'Montserrat',
                                      overflow: TextOverflow.ellipsis,
                                      color: AppTheme.colors.textCyanLight,
                                      fontSize: 14.0,
                                      letterSpacing: 1.0),
                                ),
                              ),
                            )),
                          ],
                        ),
                      ),
                      Container(
                        width: 350,
                        margin: EdgeInsets.only(
                          top: 177,
                        ),
                        child: ReactiveFormConsumer(
                          builder: (context, form, child) {
                            return Container(
                              decoration: BoxDecoration(
                                color: Colors.blueGrey.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(7),
                              ),
                              padding: EdgeInsets.all(9),
                              child: ElevatedButton(
                                style: _appButtonStyles.loginButtonStyle(),
                                onPressed: () {
                                  if (form.valid) {
                                    _passWord = form.control('password').value;
                                    _userName = form.control('username').value;
                                    _rememberme =
                                        form.control('remember').value;
                                    _login(_userName, _passWord, _rememberme);
                                  } else {
                                    form.markAllAsTouched();
                                  }
                                },
                                child: Text('Login'.tr,
                                    style: TextStyle(
                                      fontFamily: 'Montserrat',
                                    )),
                              ),
                            );
                          },
                        ),
                      ),
                      Container(
                        width: 350,
                        margin: EdgeInsets.only(
                          top: 260,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              decoration: BoxDecoration(
                                color: Colors.blueGrey.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(7),
                              ),
                              padding: EdgeInsets.all(9),
                              child: TextButton(
                                style: TextButton.styleFrom(
                                  elevation: 2,
                                  shadowColor: Colors.white,
                                  backgroundColor:
                                      Colors.orange.withOpacity(0.5),
                                  padding: EdgeInsets.all(19),
                                ),
                                onPressed: () {
                                  Get.to(() => LoginCardScanner());
                                },
                                child: Text(
                                  'Badge Login'.tr,
                                  style: TextStyle(
                                    fontFamily: 'Montserrat',
                                    color: Colors.white,
                                    fontSize: 15.0,
                                    letterSpacing: 1.0,
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              decoration: BoxDecoration(
                                color: Colors.blueGrey.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(7),
                              ),
                              padding: EdgeInsets.all(9),
                              child: TextButton(
                                style: TextButton.styleFrom(
                                  elevation: 2,
                                  shadowColor: Colors.white,
                                  backgroundColor:
                                      Colors.deepPurple.withOpacity(0.5),
                                  padding: EdgeInsets.all(19),
                                ),
                                onPressed: () {
                                  String _cleverUrl =
                                      "https://clever.com/oauth/authorize?response_type=code&redirect_uri=https%3A%2F%2F${Constants.BaseDomain}%2Fclever%2Fauth.php&client_id=${Constants.CleverClientId}";
                                  launchInWebViewWithJavaScript(_cleverUrl);
                                },
                                child: Text('Clever Login'.tr,
                                    style: TextStyle(
                                        fontFamily: 'Montserrat',
                                        color: Colors.white,
                                        fontSize: 15.0,
                                        letterSpacing: 1.0)),
                              ),
                            ),
                          ],
                        ),
                      ),
                        Container(
                        width: 350,
                        margin: EdgeInsets.only(
                          top: 330,
                        ),
                        child: Visibility(
                          visible: GetPlatform.isWeb,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                  color: Colors.blueGrey.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(7),
                                ),
                                padding: EdgeInsets.all(9),
                                child: TextButton(
                                  style: TextButton.styleFrom(
                                    elevation: 2,
                                    shadowColor: Colors.white,
                                    backgroundColor: AppTheme
                                        .colors.parentButton
                                        .withOpacity(0.5),
                                    padding: EdgeInsets.all(19),
                                  ),
                                  onPressed: () {
                                    String _parentUrl =
                                        "https://ichinesereader.com/icr/account/create/parent";
                                    launchInWebViewWithJavaScript(_parentUrl);
                                  },
                                  child: Text(
                                    '+ Parent Account'.tr,
                                    style: TextStyle(
                                        fontFamily: 'Montserrat',
                                        color: Colors.white,
                                        fontSize: 15.0,
                                        letterSpacing: 1.0),
                                  ),
                                ),
                              ),
                              Container(
                                decoration: BoxDecoration(
                                  color: Colors.blueGrey.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(7),
                                ),
                                padding: EdgeInsets.all(9),
                                child: TextButton(
                                  style: TextButton.styleFrom(
                                    elevation: 2,
                                    shadowColor: Colors.white,
                                    backgroundColor: AppTheme.colors.enableBtn
                                        .withOpacity(0.9),
                                    padding: EdgeInsets.all(19),
                                  ),
                                  onPressed: () {
                                    showGeneralDialog(
                                        context: context,
                                        transitionDuration:
                                            Duration(milliseconds: 0),
                                        pageBuilder: (bc, ania, anis) {
                                          return RoleChoose();
                                        });
                                    // String _signupUrl =
                                    //     "https://ichinesereader.com/icr/account/create/individual";
                                    // launchInWebViewWithJavaScript(_signupUrl);
                                  },
                                  child: Text(
                                    'Sign Up'.tr,
                                    style: TextStyle(
                                      fontFamily: 'Montserrat',
                                      color: Colors.white,
                                      fontSize: 15.0,
                                      letterSpacing: 1.0,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
